package com.v1.video.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.SearchThemeObj;
import com.v1.video.domain.SearchThemePageInfo;
import com.v1.video.domain.ThemeInfo;
import com.v1.video.option.util.SearchAboutUtil;
import com.v1.video.util.DensityUtil;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;

/***
 * 搜索话题
 * @author fengtao
 * 
 */
public class SearchMoreThemeActivity extends BaseActivity{
		
	private static String TAG = "SearchMoreThemeActivity";
	private TextView txtResultTips = null;
	private ArrayList<ThemeInfo> listTheme = new ArrayList<ThemeInfo>();
	private ContentAdapter adapter = new ContentAdapter();
	private String keyWord = "";
	private int pageSize = 20;
	private int pageIndex = 1;
	
	private PullToRefreshListView mContentLv;
	private ListView mContent;
	private ContentListAdapter mContentAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_theme);
		
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
//		gridViewTheme = (GridView)findViewById(R.id.theme_gridview);
		txtResultTips = (TextView)findViewById(R.id.theme_tips);
		mContentLv = (PullToRefreshListView) findViewById(R.id.lv_content);
		mContentLv.setScrollingWhileRefreshingEnabled(false);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		((TextView)findViewById(R.id.tv_title)).setText(R.string.search_theme_tips_result);
		//((TextView)findViewById(R.id.tv_result)).setText(R.string.cancel);
		Intent intent = this.getIntent();
		String mSearchStr = intent.getStringExtra("searchTxt");
		keyWord = mSearchStr;
		String str=this.getResources().getString(
				R.string.search_more_theme_title,
				mSearchStr,
				intent.getIntExtra("recordNum", 0));
		
		txtResultTips.setText(str);
//		gridViewTheme.setAdapter(adapter);
		mContent = mContentLv.getRefreshableView();
		mContent.setBackgroundDrawable(null);
		mContentLv.setDividerDrawable(null);
		mContentLv.setBackgroundDrawable(null);
//		mContentLv.setMode(Mode.BOTH);// 同时由下拉刷新和上啦加载更多
		// mContentLv.setMode(Mode.PULL_FROM_START);//只有下拉刷新
		 mContentLv.setMode(Mode.PULL_FROM_END);//只有上啦加载更多
		mContentAdapter = new ContentListAdapter();
		mContent.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mContent.setAdapter(mContentAdapter);
		new GetDataAsync(pageIndex).execute();
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		mContentLv.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				pageIndex = 1;
				new GetDataAsync(pageIndex).execute();

			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				new GetDataAsync(++pageIndex).execute();
			}
		});
	}

	@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
	
	/**
     * 检测版本
     */
    private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {
        
        private String errorMsg = "";
        
        private ProgressDialog pd;
        private SearchThemePageInfo themePageInfo;
        private int pageIndex;
        public GetDataAsync(int pageIndex) {                        
        	this.pageIndex = pageIndex;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(SearchMoreThemeActivity.this,getResources().getString(R.string.get_data), this);
            pd.show();
        }
        
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
            	SearchAboutUtil search = new SearchAboutUtil();
            	themePageInfo = search.getThemeBySearch(keyWord, ""+pageSize, ""+pageIndex);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return false;
            
        }
        @Override
		protected void onCancelled() {
			if(mContentLv != null){
				mContentLv.onRefreshComplete();
			}
			super.onCancelled();
		}
//        Uri uri = Uri.parse(versionInfo.url); 
//        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//        startActivity(it);
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }            
            
            if (errorMsg.equals("")) {
            	if(themePageInfo != null){
					if(themePageInfo.getObj() != null){
						SearchThemeObj obj = themePageInfo.getObj();
						if(obj.getList() != null){
							String str=SearchMoreThemeActivity.this.getResources().getString(
									R.string.search_more_theme_title,
									keyWord,
									obj.getPaginator().getItems());
							Utility.ChangeTextViewPartWordsTextColor(txtResultTips, str,
									SearchMoreThemeActivity.this.getResources().getColor(R.color.title_alpha_blue), 
									keyWord);
//							titleTxt.setText(str);
							if(pageIndex == 1){
								listTheme.clear();
								listTheme.addAll(obj.getList());
							}else{
								listTheme.addAll(obj.getList());
							}
							if(obj.getList().size() < pageSize){
								mContentLv.setMode(Mode.PULL_DOWN_TO_REFRESH);
								pageIndex = 1;
							}else{
								mContentLv.setMode(Mode.BOTH);
							}
							if(mContentAdapter == null){
								mContentAdapter = new ContentListAdapter();
								mContent.setAdapter(mContentAdapter);
							}else{
								mContentAdapter.notifyDataSetChanged();
							}
							adapter.notifyDataSetChanged();
						}else{
							ToastAlone
							.showToast(SearchMoreThemeActivity.this, "没有数据", 1);
						}
					}else{
						ToastAlone
						.showToast(SearchMoreThemeActivity.this, themePageInfo.getMsg(), 1);
					}
				}else{
					ToastAlone
					.showToast(SearchMoreThemeActivity.this, "未知错误", 1);
				}
            	if(mContentLv != null){
            		mContentLv.onRefreshComplete();
            	}
            } else {
                ToastAlone.showToast(SearchMoreThemeActivity.this, errorMsg, 1);
                if(mContentLv != null){
            		mContentLv.onRefreshComplete();
            	}
            }
        }
    }
    
    private class ContentListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder = null;
//			final Group group = mGroupsInfos.get(position);
			if (convertView == null) {
				convertView = LayoutInflater.from(SearchMoreThemeActivity.this)
						.inflate(R.layout.item_theme_listview, null);
				holder = new PlaceHolder();
				holder.gridViewTheme=(GridView)convertView.findViewById(R.id.theme_gridview);
				
				convertView.setTag(holder);
			} else {
				holder = (PlaceHolder) convertView.getTag();
			}
			LayoutParams layoutParams = holder.gridViewTheme.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(SearchMoreThemeActivity.this, 50*listTheme.size());
            layoutParams.width = LayoutParams.MATCH_PARENT;
            holder.gridViewTheme.setLayoutParams(layoutParams);
			holder.gridViewTheme.setAdapter(adapter);
			return convertView;
		}

		private class PlaceHolder {
			
			GridView gridViewTheme;
		}
	}
    
    private class ContentAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listTheme.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return listTheme.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PlaceHolder holder = null;
//			final Group group = mGroupsInfos.get(position);
			final ThemeInfo themeInfo = listTheme.get(position);
			if (convertView == null) {
				convertView = LayoutInflater.from(SearchMoreThemeActivity.this)
						.inflate(R.layout.search_more_theme_item, null);
				holder = new PlaceHolder();
				holder.themeName=(TextView)convertView.findViewById(R.id.item_theme_content);
				
				convertView.setTag(holder);
			} else {
				holder = (PlaceHolder) convertView.getTag();
			}
//			Utility.ChangeTextViewPartWordsTextColor(
//					holder.quanziName, 
//					(position + 1) + "欢迎加入"+mSearchStr+"馆", 
//					SearchMoreQuanziActivity.this.getResources().getColor(R.color.title_alpha_blue), 
//					mSearchStr);
			
//			if(themeInfo.getAname().equals("") || themeInfo.getAname().equals("null") || themeInfo.getAname() == null){
//				holder.themeName.setText(themeInfo.getOaName());
//			}else{
//				holder.themeName.setText(themeInfo.getAname());
//			}
			holder.themeName.setText("#"+themeInfo.getTopicName()+"#");
			convertView.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {

				}});
			
			return convertView;
		}

		private class PlaceHolder {
			
			TextView themeName;
		}
	}
}
